package com.cash.app.ui.auth

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.provider.ContactsContract
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import androidx.activity.viewModels
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant
import com.cash.app.constant.AppConstant.AUTH_O_REQUEST_OPTION
import com.cash.app.custom.AppActionBar
import com.cash.app.databinding.AcAuthPersonalBinding
import com.cash.app.manager.AuthMetaDataManager
import com.cash.app.manager.GlobalTaskManager.getMetaData
import com.cash.app.manager.LoginManager
import com.cash.app.ui.auth.model.AuthPersonalInfoResponse
import com.cash.app.utils.hide
import com.cash.app.utils.visible

class AuthPersonalActivity : BaseActivity() {

    private var isOnlyShow = false

    companion object {
        private const val REQUEST_CONTACT_FIRST = 101
        private const val REQUEST_CONTACT_SECOND = 102
        private const val EXTRA_ONLY_SHOW = "isOnlyShow"

        fun start(context: Context, isOnlyShow: Boolean = false) {
            val intent = Intent(context, AuthPersonalActivity::class.java).apply {
                putExtra(EXTRA_ONLY_SHOW, isOnlyShow)
            }
            context.startActivity(intent)
        }
    }

    private lateinit var binding: AcAuthPersonalBinding
    private val viewModel: AuthPersonalViewModel by viewModels()

    override fun setViewBind() {
        binding = AcAuthPersonalBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View = binding.root

    override fun getAppActionBar(): AppActionBar = binding.actionBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setClickListener()
        initObserver()
        initContactView()
        isOnlyShow = intent.getBooleanExtra(EXTRA_ONLY_SHOW, false)
        if (isOnlyShow) {
            viewModel.getAuthInfoByPersonal()
        }
        getMetaData()
    }

    private fun EditText.addTextChangedListener(afterTextChanged: (String) -> Unit) {
        this.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                afterTextChanged.invoke(s?.toString() ?: "")
            }
        })
    }

    private fun initContactView() {
        if (LoginManager.isCheck()) {
            binding.apply {
                firstAddContactLayout.hide()
                secAddContactLayout.hide()
                firstContactWriteCl.visible()
                secondContactWriteCl.visible()

                firstContactWriteName.addTextChangedListener { text ->
                    viewModel.firstContactName = text
                }
                firstContactWritePhone.addTextChangedListener { text ->
                    viewModel.firstContactPhone = text
                }
                secondContactWriteName.addTextChangedListener { text ->
                    viewModel.secondContactName = text
                }
                secondContactWritePhone.addTextChangedListener { text ->
                    viewModel.secondContactPhone = text
                }

                // Set initial values if available
                firstContactWriteName.setText(viewModel.firstContactName)
                firstContactWritePhone.setText(viewModel.firstContactPhone)
                secondContactWriteName.setText(viewModel.secondContactName)
                secondContactWritePhone.setText(viewModel.secondContactPhone)
            }
        } else {
            binding.firstAddContactLayout.visible()
            binding.secAddContactLayout.visible()
            binding.firstContactWriteCl.hide()
            binding.secondContactWriteCl.hide()
        }
    }

    private fun initObserver() {
        viewModel.submitSuccess.observe(this) {
            //Toast.makeText(this, getString(R.string.auth_success), Toast.LENGTH_SHORT).show()
            val intent = Intent(this, AuthBankActivity::class.java)
            startActivity(intent)

            setResult(Activity.RESULT_OK)
            finish()
        }
        viewModel.authPersonalInfo.observe(this) { personInfo: AuthPersonalInfoResponse ->
            binding.apply {
                btnSubmit.hide()
                val metaData = AuthMetaDataManager.getMetaData()
                educationValue.text = metaData?.education?.get(personInfo.personalEducate)
                maritalValue.text = metaData?.marriage?.get(personInfo.personalMarry)
                childrenValue.text = metaData?.child?.get(personInfo.personalChildNum)
                careerValue.text = metaData?.industryType?.get(personInfo.personalWorkType)
                incomeValue.text = metaData?.marriage?.get(personInfo.personalWorkMoney)
                relativeValue.text = metaData?.emergency1?.get(personInfo.personalDirectRelation)
                firstContactValue.text =
                    personInfo.personalDirectName.plus("," + personInfo.personalDirectPhone)
                secRelativeValue.text = metaData?.emergency2?.get(personInfo.personalOtherRelation)
                secondContactValue.text =
                    personInfo.personalOtherName.plus("," + personInfo.personalOtherPhone)
                emailValue.setText(personInfo.personalEmail)
                emailValue.isEnabled = false
                tvEmailTip.hide()
            }
        }
    }

    private fun setClickListener() {
        binding.apply {
            educationLayout.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                viewModel.currentOptionType = AppConstant.AUTH_O_EDUCATION
                AuthPersonalOptionActivity.start(
                    this@AuthPersonalActivity, AppConstant.AUTH_O_EDUCATION
                )
            }
            maritalLayout.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                viewModel.currentOptionType = AppConstant.AUTH_O_MARITAL
                AuthPersonalOptionActivity.start(
                    this@AuthPersonalActivity, AppConstant.AUTH_O_MARITAL
                )
            }
            childrenLayout.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                viewModel.currentOptionType = AppConstant.AUTH_O_CHILDREN
                AuthPersonalOptionActivity.start(
                    this@AuthPersonalActivity, AppConstant.AUTH_O_CHILDREN
                )
            }
            careerLayout.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                viewModel.currentOptionType = AppConstant.AUTH_O_CAREER
                AuthPersonalOptionActivity.start(
                    this@AuthPersonalActivity, AppConstant.AUTH_O_CAREER
                )
            }
            incomeLayout.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                viewModel.currentOptionType = AppConstant.AUTH_O_INCOME
                AuthPersonalOptionActivity.start(
                    this@AuthPersonalActivity, AppConstant.AUTH_O_INCOME
                )
            }
            firstRelationshipLayout.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                viewModel.currentOptionType = AppConstant.AUTH_O_FIRST_CONTACT
                AuthPersonalOptionActivity.start(
                    this@AuthPersonalActivity, AppConstant.AUTH_O_FIRST_CONTACT
                )
            }
            secRelationshipLayout.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                viewModel.currentOptionType = AppConstant.AUTH_O_SECOND_CONTACT
                AuthPersonalOptionActivity.start(
                    this@AuthPersonalActivity, AppConstant.AUTH_O_SECOND_CONTACT
                )
            }
            firstAddContactLayout.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                pickContact(REQUEST_CONTACT_FIRST)
            }

            secAddContactLayout.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                pickContact(REQUEST_CONTACT_SECOND)
            }

            btnSubmit.setOnClickListener {
                if (isOnlyShow) {
                    return@setOnClickListener
                }
                viewModel.submitStepTwo(
                    this@AuthPersonalActivity, emailValue.text.toString()
                )
            }
        }
    }

    private fun pickContact(requestCode: Int) {
        val intent = Intent(Intent.ACTION_PICK).apply {
            type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
        }
        startActivityForResult(intent, requestCode)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                AUTH_O_REQUEST_OPTION -> handleOptionResult(data)
                REQUEST_CONTACT_FIRST, REQUEST_CONTACT_SECOND -> handleContactResult(
                    requestCode, data
                )
            }
        }
    }

    private fun handleOptionResult(data: Intent) {
        val selectedId = data.getStringExtra(AuthPersonalOptionActivity.EXTRA_SELECTED_ID)
        val selectedValue = data.getStringExtra(AuthPersonalOptionActivity.EXTRA_SELECTED_VALUE)

        if (selectedId != null && selectedValue != null) {
            binding.apply {
                when (viewModel.currentOptionType) {
                    AppConstant.AUTH_O_EDUCATION -> {
                        educationValue.text = selectedValue
                        viewModel.educationId = selectedId
                    }

                    AppConstant.AUTH_O_MARITAL -> {
                        maritalValue.text = selectedValue
                        viewModel.maritalId = selectedId
                    }

                    AppConstant.AUTH_O_CHILDREN -> {
                        childrenValue.text = selectedValue
                        viewModel.childrenNumId = selectedId
                    }

                    AppConstant.AUTH_O_CAREER -> {
                        careerValue.text = selectedValue
                        viewModel.careerId = selectedId
                    }

                    AppConstant.AUTH_O_INCOME -> {
                        incomeValue.text = selectedValue
                        viewModel.incomeId = selectedId
                    }

                    AppConstant.AUTH_O_FIRST_CONTACT -> {
                        relativeValue.text = selectedValue
                        viewModel.firstContactId = selectedId
                    }

                    AppConstant.AUTH_O_SECOND_CONTACT -> {
                        secRelativeValue.text = selectedValue
                        viewModel.secondContactId = selectedId
                    }
                }
            }
        }
    }

    private fun handleContactResult(requestCode: Int, data: Intent) {
        val contactUri = data.data ?: return
        val projection = arrayOf(
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
        )

        contentResolver.query(
            contactUri, projection, null, null, null
        )?.use { cursor ->
            if (cursor.moveToFirst()) {
                val nameIndex =
                    cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                val numberIndex =
                    cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

                val name = cursor.getString(nameIndex)
                val number = cursor.getString(numberIndex)?.replace(Regex("[^0-9]"), "")

                when (requestCode) {
                    REQUEST_CONTACT_FIRST -> {
                        viewModel.firstContactName = name
                        viewModel.firstContactPhone = number ?: ""
                        binding.firstContactValue.text =
                            name.plus("," + viewModel.firstContactPhone)
                    }

                    REQUEST_CONTACT_SECOND -> {
                        viewModel.secondContactName = name
                        viewModel.secondContactPhone = number ?: ""
                        binding.secondContactValue.text =
                            name.plus("," + viewModel.secondContactPhone)
                    }
                }
            }
        }
    }
}